package com.example.service;

import cn.hutool.core.date.DateUtil;
import com.example.entity.Account;
import com.example.entity.Admin;
import com.example.exception.CustomerException;
import com.example.mapper.AdminMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminService {

    @Resource
    AdminMapper adminMapper;

    public void add(Admin admin) {
        //  判断用户名是否存在
        Admin dbAdmin = adminMapper.selectByUsername(admin.getUsername());
        if (dbAdmin != null){
            throw new CustomerException("用户名已存在");
        }
        // 密码为空时，默认为admin
        if (StringUtils.isBlank(admin.getPassword())){
            admin.setPassword("admin");
        }
        admin.setRole("ADMIN");
        admin.setTime(DateUtil.now());
        adminMapper.insert(admin);
    }

    public void delete(Integer id) {
        adminMapper.deleteById(id);
    }

    public void update(Admin admin) {
        adminMapper.updateById(admin);
    }

    public List<Admin> selectAll(Admin admin) {
        Account currentUser = TokenUtils.getCurrentUser();
        admin = adminMapper.selectById(currentUser.getId());
        return adminMapper.selectAll(admin);
    }


    public PageInfo<Admin> selectPage(Integer pageNum, Integer pageSize, Admin admin) {
        // 开启分页查询
        PageHelper.startPage(pageNum, pageSize);
        List<Admin> list = adminMapper.selectAll(admin);
        return PageInfo.of(list);
    }


    public Admin selectById(Integer userId) {
        return adminMapper.selectById(userId);
    }

    public Admin login(Account account) {
        // 验证账号是否存在
        Admin dbAdmin = adminMapper.selectByUsername(account.getUsername());
        if (dbAdmin == null){
            throw new CustomerException("账号不存在");
        }
        // 验证密码是否正确
        if (!dbAdmin.getPassword().equals(account.getPassword())){
            throw new CustomerException("密码错误");
        }
        // 创建token并返回给前端
        String token = TokenUtils.createToken(dbAdmin.getId() + "-" + "ADMIN", dbAdmin.getPassword());
        dbAdmin.setToken(token);
        return dbAdmin;
    }
}
